<script setup>
import { useRoute ,useRouter} from 'vue-router';
import {ref,computed} from 'vue';
import {getExpenseDetail} from "@/api/accountDetail/detail.js";
import {getRequest,updateRequest} from "@/api/requestDeal/deal.js";
import AMapLoader from '@amap/amap-jsapi-loader';
const input = ref('')
const loading = ref(true)
const route = useRoute();
const status = route.params.status
const id = computed(() => route.params.id);
const isProcessed = ref(false);
const router = useRouter();
const requestInfo = ref({
  realName:'',
  helpType:'',
  helpLocation:'',
  phoneNumber:'',
  helpTime:'',
  helpDesc:'',
  handleOpinion: '',
  status:''
})
function getRequestInfo(){
  loading.value = true
  getRequest(id.value).then(response => {
    console.log(response)
    requestInfo.value = response.data
    console.log("接口返回的handleOpinion：", requestInfo.value.handleOpinion);
    isProcessed.value = requestInfo.value.status === '已处理';
    input.value = requestInfo.value.handleOpinion || '';
    console.log(isProcessed.value)
    loading.value = false
    initMap()
  })
}
function handleSubmit() {
  if (!input.value.trim()) {
    alert('请输入处理意见');
    return;
  }

  const updateData = {
    id: id.value,
    status: '已处理',
    handleOpinion: input.value,
  };
  updateRequest(updateData).then(() => {
    alert('处理成功');
    getRequestInfo()
    router.back();
  }).catch(error => {
    alert('处理失败，请重试');
  });

}

function initMap() {
  // 先判断地址是否存在，避免地图初始化失败
  if (!requestInfo.value.helpLocation) {
    console.warn('求助位置为空，不初始化地图');
    return;
  }

  window._AMapSecurityConfig = {
    securityJsCode: "b9c406b1c79e4e25086a162f1924522f",
  };

  AMapLoader.load({
    key: "39410e5b7d34faa7b8a9bdbc22722856",
    version: "2.0"
  }).then((AMap) => {
    AMap.plugin('AMap.Geocoder', function() {
      const geocoder = new AMap.Geocoder({ city: '全国' });

      geocoder.getLocation(requestInfo.value.helpLocation, function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
          const location = result.geocodes[0].location;
          const map = new AMap.Map("container", {
            zoom: 10,
            center: [location.lng, location.lat]
          });

          // 创建marker并添加到地图（修复原代码中marker未定义的错误）
          const marker = new AMap.Marker({
            position: [location.lng, location.lat]
          });
          map.add(marker);

          // 信息窗口（绑定到当前marker）
          const infoWindow = new AMap.InfoWindow({
            isCustom: true,
            content: `<div>${requestInfo.value.helpLocation}</div>`,
            offset: new AMap.Pixel(16, -45)
          });
          marker.on("click", (e) => {
            infoWindow.open(map, e.target.getPosition());
          });
        } else {
          console.error('地址解析失败：', result.info);
        }
      });
    });
  }).catch((e) => {
    console.error('地图加载失败：', e);
  });
}


getRequestInfo()

</script>

<template>
  <div class="top">账户详情</div>
  <div class="account-info">

    <div class="account-details" >
      <p>
        <span>配送员姓名：</span>{{ requestInfo.realName }}
        <span style="margin-left: 80px">求助类型：</span>{{ requestInfo.helpType }}
        <span style="margin-left: 80px">工作类型：</span>{{ requestInfo.helpLocation }}
      </p>
      <p>
        <span>手机号码：</span>{{ requestInfo.phoneNumber }}
        <span style="margin-left: 19px">求助时间：</span>{{requestInfo.helpTime}}
        <span style="margin-left: 60px">求助描述:</span>{{requestInfo.helpDesc}}
      </p>
    </div>
  </div>
  <div id="container" style="width: 100%; height: 600px;"></div>
  <div style="margin-top: 30px">
    处理意见：
    <div v-if="isProcessed" class="readonly-opinion">
      {{ requestInfo.handleOpinion }}
    </div>
    <div v-else>
      <el-input v-model="input" style="width: 600px" placeholder="请输入处理意见" />
      <el-button type="primary" style="margin-left: 20px" @click="handleSubmit">确定</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.account-info {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #EBF2FE;
  margin-bottom: 10px;
}
.account-details p {
  margin: 5px 0;
}

.account-details span {
  font-weight: bold;
}
.readonly-opinion {
  display: inline-block;
  width: 600px;
  min-height: 40px;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
  vertical-align: middle;
}
</style>